package com.example.art_cloud_backend.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.art_cloud_backend.exception.BusinessException;
import com.example.art_cloud_backend.exception.ErrorCode;
import com.example.art_cloud_backend.exception.ThrowUtils;
import com.example.art_cloud_backend.model.constant.UserConstant;
import com.example.art_cloud_backend.model.dto.user.UserLoginRequest;
import com.example.art_cloud_backend.model.dto.user.UserQueryRequest;
import com.example.art_cloud_backend.model.entity.User;
import com.example.art_cloud_backend.model.dto.user.UserRegisterRequest;
import com.example.art_cloud_backend.model.enums.UserRoleEnum;
import com.example.art_cloud_backend.model.vo.user.LoginUserVO;
import com.example.art_cloud_backend.model.vo.user.UserVO;
import com.example.art_cloud_backend.service.UserService;
import com.example.art_cloud_backend.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2025-07-27 17:25:13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    /**
     * 用户注册
     * @param userRegisterRequest 用户注册请求参数
     * @return 新用户id
     */
    @Override
    public Long userRegister(UserRegisterRequest userRegisterRequest) {
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkUserPassword = userRegisterRequest.getCheckUserPassword();
        // 1. 校验参数
        ThrowUtils.throwIf(CharSequenceUtil.hasBlank(userAccount, userPassword, checkUserPassword), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号长度不能小于4位");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkUserPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
        ThrowUtils.throwIf(!userPassword.equals(checkUserPassword), ErrorCode.PARAMS_ERROR, "两次输入密码不一致");
        // 2. 检查重复
        User user = this.baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userAccount));
        ThrowUtils.throwIf(ObjectUtil.isNotNull(user), ErrorCode.PARAMS_ERROR, "账号重复");
        // 3. 密码加密
        String encryptPassword = this.getEncryptPassword(userPassword);
        // 4. 插入数据
        user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        // 设置默认角色
        user.setUserRole(UserConstant.DEFAULT_ROLE);
        // 设置默认昵称
        user.setUserName(userAccount);
        boolean result = this.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "注册失败");
        return user.getId();
    }

    /**
     * 用户登录
     *
     * @param userLoginRequest 用户登录请求参数
     * @return 登录成功返回用户信息，登录失败返回null
     */
    @Override
    public LoginUserVO userLogin(UserLoginRequest userLoginRequest, HttpServletRequest request) {
        // 1. 校验参数
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        ThrowUtils.throwIf(CharSequenceUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号长度不能小于4位");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码长度不能小于8位");
        // 2. 检查用户是否存在
        // 加密密码
        String encryptPassword = this.getEncryptPassword(userPassword);
        User user = this.baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserAccount, userAccount).eq(User::getUserPassword, encryptPassword));
        ThrowUtils.throwIf(ObjectUtil.isNull(user), ErrorCode.PARAMS_ERROR, "账号或密码错误");
        // 3. 记录用户的登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);
        // 4. 返回脱敏信息
        return this.getLoginUserVO(user);
    }

    /**
     * 获取当前登录用户信息
     * @param request 请求参数
     * @return 登录成功返回用户信息，登录失败返回null
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(ObjectUtil.isNull(currentUser) || currentUser.getId() == null, ErrorCode.NOT_LOGIN);
        // 从数据库查询
        Long userId = currentUser.getId();
        currentUser = this.getById(userId);
        ThrowUtils.throwIf(ObjectUtil.isNull(currentUser), ErrorCode.NOT_LOGIN);
        // 返回脱敏信息
        return currentUser;
    }

    /**
     * 用户注销
     * @param request 请求参数
     * @return 注销成功返回true，注销失败返回false
     */
    @Override
    public Boolean userLogout(HttpServletRequest request) {
        // 判断是否登录
        User loginUser = this.getLoginUser(request);
        ThrowUtils.throwIf(ObjectUtil.isNull(loginUser), ErrorCode.NOT_LOGIN);
        // 注销登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    /**
     * 获取登录用户脱敏后的信息
     *
     * @param user 用户信息
     * @return 登录用户信息
     */
    @Override
    public LoginUserVO getLoginUserVO(User user) {
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    /**
     * 获取查询条件
     * @param userQueryRequest 查询参数
     * @return 查询条件
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull(id), "id", id);
        queryWrapper.eq(StrUtil.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.like(StrUtil.isNotBlank(userAccount), "userAccount", userAccount);
        queryWrapper.like(StrUtil.isNotBlank(userName), "userName", userName);
        queryWrapper.like(StrUtil.isNotBlank(userProfile), "userProfile", userProfile);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 获取用户脱敏后的信息
     * @param user 用户信息
     * @return 用户信息
     */
    @Override
    public UserVO getUserVO(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    /**
     * 获取用户列表脱敏后的信息
     * @param userList 用户列表
     * @return 用户列表
     */
    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    /**
     * 密码加密
     *
     * @param password 密码
     * @return 加密后的密码
     */
    @Override
    public String getEncryptPassword(String password) {
        // 盐值
        String salt = "cymc_art_cloud";
        // 加密
        return DigestUtils.md5DigestAsHex((salt + password).getBytes());
    }

    /**
     * 判断用户是否为管理员
     * @param user 用户信息
     * @return 是否为管理员
     */
    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getRoleValue().equals(user.getUserRole());
    }
}




